package com.fbs.wowo.correctRight.service.imp;

import com.fbs.wowo.correctRight.entity.CopyrightWorksType;
import com.fbs.wowo.correctRight.entity.CorrectRight;
import com.fbs.wowo.correctRight.entity.CorrectRightInfo;
import com.fbs.wowo.correctRight.mapper.CorrectRightMapper;
import com.fbs.wowo.correctRight.service.CopyrightWorksTypeService;
import com.fbs.wowo.correctRight.service.CorrectRightService;
import com.fbs.wowo.correctRight.vo.CorrectRightQuery;
import com.fbs.wowo.essay.entity.Essay;
import com.fbs.wowo.essay.mapper.EssayMapper;
import com.fbs.wowo.exception.DataOverflowException;
import com.fbs.wowo.exception.ErrorCode;
import com.fbs.wowo.manage.entity.Account;
import com.fbs.wowo.manage.entity.AccountDetail;
import com.fbs.wowo.manage.entity.User;
import com.fbs.wowo.manage.mapper.AccountDetailMapper;
import com.fbs.wowo.manage.mapper.AccountMapper;
import com.fbs.wowo.manage.service.UserService;
import com.fbs.wowo.util.common.ComUtils;
import com.fbs.wowo.util.eos.EOSService;
import com.fbs.wowo.util.eos.EOSServiceImp;
import com.fbs.wowo.util.watermark.QrCodeUtil;
import com.fbs.wowo.util.watermark.WaterMarkUtils;
import com.fbs.wowo.works.entity.Works;
import com.fbs.wowo.works.mapper.WorksMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;

/**
 * 确权
 */
@Service("CorrectRightService")
@Transactional
public class CorrectRightServiceImp implements CorrectRightService {

    @Resource
    private CorrectRightMapper correctRightMapper;

    @Resource
    private UserService userService;

    @Resource
    private EssayMapper essayMapper;

    @Resource
    private AccountMapper accountMapper;

    @Resource
    private EOSService eosService;

    @Resource
    private WorksMapper worksMapper;

    @Resource
    private AccountDetailMapper accountDetailMapper;

    @Resource
    private CopyrightWorksTypeService copyrightWorksTypeService;


    @Value("${HOST_ADDRESS}")
    private String HOST_ADDRESS;

    /**
     * 添加确权数据
     *
     * @param record
     * @return
     */
    @Override
    public int insertSelective(CorrectRight record) {
        record.setId(ComUtils.getUUID());
        record.setCreateDate(new Date());
        String essayId = record.getEssayId();
        Essay essay = essayMapper.selectByPrimaryKey(essayId);
        CorrectRight corr = correctRightMapper.findCorrectRightByEssayId(record.getEssayId());
        if (corr != null) {
            throw new DataOverflowException(ErrorCode.ERR_DATA_HAS_EXIST);
        } else {
            if (essay != null) {
                //是否已实名认证
                User user = userService.findByUserId(essay.getUserId());
                if (user != null) {
                    if (user.getUserId()!=null && !user.getUserId().equals("")){
                        AccountDetail accountDetail = accountDetailMapper.findByUserId(user.getUserId());
                        if (accountDetail!=null){
                            if (accountDetail.getCertStatus()==2){
                                //修改确权状态
                                essay.setConfirmed((byte) 1);
                                essayMapper.updateByPrimaryKeySelective(essay);
                                return correctRightMapper.insertSelective(record);
                            }
                        }
                    }
                    throw new DataOverflowException(ErrorCode.ERR_CER_NULL);
                }
                throw new DataOverflowException(ErrorCode.ERR_USER_NOT_EXIST);
            }
            throw new DataOverflowException(ErrorCode.ERR_NULL_DATA);
        }
    }

    @Override
    public CorrectRight selectByPrimaryKey(String id) {
        return correctRightMapper.selectByPrimaryKey(id);
    }

    @Override
    public CorrectRightInfo findCorrectRightInfoByEssayId(String essayId) {
        return correctRightMapper.findCorrectRightInfoByEssayId(essayId);
    }


    @Override
    public int updateByPrimaryKeySelective(CorrectRight record) {
        return correctRightMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int deleteByEssayId(String essayId) {
        Essay essay = essayMapper.selectByPrimaryKey(essayId);
        if (essay != null) {
            //修改确权状态
            essay.setConfirmed((byte) 0);
            essayMapper.updateByPrimaryKeySelective(essay);
        }
        return correctRightMapper.deleteByEssayId(essayId);
    }

    @Override
    public List<CorrectRightInfo> findCorrectRightList(CorrectRightQuery crq) {
        return correctRightMapper.findCorrectRightList(crq);
    }


    /**
     * 审核成功
     *
     * @param articleId ID
     * @param type      1手机端  2电脑端
     * @return
     */
    @Override
    public int reviewTheSuccess(String articleId, int type) {
        CorrectRight corr = correctRightMapper.findCorrectRightByEssayId(articleId);
        if (corr != null) {
            if (type == 1) {
                Essay essay = essayMapper.selectByPrimaryKey(articleId);
                if (essay!=null){
                    Account account = accountMapper.findByUserId(essay.getUserId());
                    if (account != null) {
                        //图文
                        if (essay.getType() == 1) {
                            EOSServiceImp.EosTransactionResponse eos =
                                    eosService.imagetextAuthright(essay.getUserId(), account.getPrivateKey(), essay.getHashValue());
                            corr.setBlockHeight(eos.getBlockNum());
                            corr.setRegisterId(eos.getTransactionId());
                            corr.setChainId(eos.getChainId());
                        } else if (essay.getType() == 2) {
                            EOSServiceImp.EosTransactionResponse eos =
                                    eosService.audioAuthright(essay.getUserId(), account.getPrivateKey(), essay.getHashValue());
                            corr.setBlockHeight(eos.getBlockNum());
                            corr.setRegisterId(eos.getTransactionId());
                            corr.setChainId(eos.getChainId());
                        }
                        //设置证书
                        String worksTypeId = corr.getWorksTypeId();
                        CopyrightWorksType cop = copyrightWorksTypeService.selectByPrimaryKey(worksTypeId);
                        if (cop != null) {
                            LocalDate now = LocalDate.now();
                            int year = now.getYear();
                            int month = now.getMonthValue();
                            int day = now.getDayOfMonth();
                            String date = year + "年" + month + "月" + day + "日";
                            //二维码
                            String infoUrl = HOST_ADDRESS + "dataDetail?essayId=" + articleId+"&type=1";
                            String path = FileSystemView.getFileSystemView().getHomeDirectory() + File.separator + "testQrcode";
                            String fileName = "temp.jpg";
                            String smallImgPath = QrCodeUtil.createQrCode(infoUrl, path, fileName);
                            String url = WaterMarkUtils.addWaterMark
                                    //二维码,作品名称,类别名称,作者,归属人,认证时间
                                            (smallImgPath, essay.getHashValue(), corr.getWorksName(), cop.getTitle(), corr.getAuthor(), corr.getBelonger(), date);
                            corr.setCertificateImg(url);
                            corr.setCreateDate(new Date());
                            correctRightMapper.updateByPrimaryKeySelective(corr);
                            essay.setConfirmed((byte) 2);
                            essayMapper.updateByPrimaryKeySelective(essay);
                            return 1;
                        }
                    }
                    throw new DataOverflowException(ErrorCode.ERR_NULL_DATA);
                }
                throw new DataOverflowException(ErrorCode.ERR_ESSAY_NULL);
            } else if (type == 2) {
                Works works = worksMapper.selectByPrimaryKey(articleId);
                if (works!=null){
                    Account account = accountMapper.findByUserId(works.getUserId());
                    if (account != null) {
                        //确权
                        EOSServiceImp.EosTransactionResponse eos =
                                eosService.imagetextAuthright(works.getUserId(), account.getPrivateKey(), works.getHashValue());
                        corr.setBlockHeight(eos.getBlockNum());
                        corr.setRegisterId(eos.getTransactionId());
                        corr.setChainId(eos.getChainId());
                    }
                    //设置证书
                    String worksTypeId = corr.getWorksTypeId();
                    CopyrightWorksType cop = copyrightWorksTypeService.selectByPrimaryKey(worksTypeId);
                    if (cop != null) {
                        LocalDate now = LocalDate.now();
                        int year = now.getYear();
                        int month = now.getMonthValue();
                        int day = now.getDayOfMonth();
                        String date = year + "年" + month + "月" + day + "日";
                        //二维码
                        String infoUrl = HOST_ADDRESS + "dataDetail?essayId=" + articleId+"&type=2";
                        String path = FileSystemView.getFileSystemView().getHomeDirectory() + File.separator + "testQrcode";
                        String fileName = works.getId()+".jpg";
                        String smallImgPath = QrCodeUtil.createQrCode(infoUrl, path, fileName);
                        String url = WaterMarkUtils.addWaterMark
                        //二维码,作品名称,类别名称,作者,归属人,认证时间
                                        (smallImgPath, works.getHashValue(), corr.getWorksName(), cop.getTitle(), corr.getAuthor(), corr.getBelonger(), date);
                        File file = new File(smallImgPath);
                        if (file.exists() && file.isFile()) {
                            file.delete();
                            corr.setCertificateImg(url);
                            corr.setCreateDate(new Date());
                            correctRightMapper.updateByPrimaryKeySelective(corr);
                            works.setStatus((byte) 2);
                            worksMapper.updateByPrimaryKeySelective(works);
                            return 1;
                        }
                        throw new DataOverflowException(ErrorCode.ERR_FILE_NULL);
                    }
                }
            }
        }
        throw new DataOverflowException(ErrorCode.ERR_NULL_DATA);
    }


    public int reviewTheFailure(String articleId,int type) {
        if (type==2){
            Works works = worksMapper.selectByPrimaryKey(articleId);
            if (works!=null){
                works.setStatus((byte)3);
                worksMapper.updateByPrimaryKeySelective(works);
                CorrectRight corr = correctRightMapper.findCorrectRightByEssayId(works.getId());
                if (corr!=null){
                    correctRightMapper.deleteByPrimaryKey(corr.getId());
                    return 1;
                }
            }
        }
       return 0;
    }

}
